<?php

	if(!defined('YMT')) exit;

	/**
	 * @package Yomm
	 * @author bsuter
	 *
	 */
	Class Yomm_Library_Localization {
		
		protected $i18n_code = null;	
		
		public $lang = array();
		
		private $error = array();
		
		private $ext = ".lang.csv";
		
		private $fail_default = "de_CH";
		
		static private $instance = null;
		
		/**
		 * 
		 * @param $i18n_code [string] bsp. de_CH, en_EN
		 * @return void
		 */
		public function __construct($i18n_code)
		{
			if(!defined('SiteConfig::LangFiles')) // throw initial error
			{
				throw new Yomm_Error("fatal error: SiteConfig::LangFiles not defined"); echo $error->getMessage(); exit;
			}
			
			$this->i18n_code = $i18n_code; $this->load_lib();
			
			if(!array_key_exists($i18n_code, $this->lang))
			{
				$this->i18n_code = $this->fail_default; // use fail back language if default language is not available in the backend!
			}
		}
		
		/**
		 * single ton method
		 * @return 
		 */
		static public function getInstance($i18n_code)
		{
			if(self::$instance === null){
				self::$instance = new self($i18n_code);
			}
			return self::$instance;
		}
		
		public function __call($name, $args)
		{
			$_tmp = $this->get_lang($name);
			
			if($_tmp === false)
			{
				return "[the local code '{$name}' does not exists]";
			}
			
			preg_match_all("/\{([0-9]+)\}/", $_tmp, $result, PREG_SET_ORDER);
			
			foreach($result as $rgx)
			{
				if(array_key_exists($rgx[1], $args))
				{
					$_tmp = str_replace($rgx[0], $args[$rgx[1]], $_tmp);
				} else {
					$_tmp = "[argument '{$rgx[0]}' was not declared in args]";
				}
			}
			
			return $_tmp;
		}
		
		public function load_lib()
		{
			if(SiteConfig::LangFiles == "")
				return true;
			
			$files = explode(";", SiteConfig::LangFiles);
			
			foreach($files as $file)
			{
				$file_path = Yomm_Config::DIR_LANGUAGE_FILES . $file . $this->ext;
				
				$tmp = $this->read_file($file_path);
				
				if($this->isError())
				{
					throw new Yomm_Error($this->getError()); continue;
				}
				
				$this->lang = array_merge_recursive($this->lang, $tmp);
			}
		}
		
		public function get_lang($name)
		{
			if(!array_key_exists($name, $this->lang[$this->i18n_code])) return false;
			
			return $this->lang[$this->i18n_code][$name];	
		}
		
		/**
		 * write csv entrys into php array and return
		 * @param $file
		 * @return $csv [array] array(de_ch => array('world' => 'constant world says hello'));
		 */
		private function read_file($file)
		{
			if(!file_exists($file)) return $this->setError("file {$file} does not exists");
			
			if(!is_readable($file)) return $this->setError("file {$file} is not readable");
			
			// to avoid php notice			
			$handle = fopen($file, "r"); $csv = array(); $i = 0;
			// read and return
			while(($data = fgetcsv($handle, 0, ";")) !== false)
			{
				// take first key as struct header for array
				if($i == 0){
					$_ENV['keys'] = array_slice($data,1);
				}else{
					$data_sliced = array_slice($data,1);
					foreach($_ENV['keys'] as $k => $v){
						$csv[$v][$data[0]] = $data_sliced[$k];
					}
				} $i++;
			}
			fclose($handle);
			return $csv;

		}
		
		private function isError()
		{
			if(count($this->error) >= 1)
			{
				return true;
			}
			
			return false;
		}
		
		private function getError()
		{
			return print_r($this->error, true);
		}
		
		private function setError($error_msg)
		{
			$this->error[] = $error_msg;
			return false;
		}
	}